<!doctype html>




<html class="theme-next pisces" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
    
  
  <link href="//cdn.staticfile.org/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.lug.ustc.edu.cn/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="//cdn.staticfile.org/font-awesome/4.6.2/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Web,JavaScript," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="表单脚本表单的基础知识HTML 对应： &amp;lt;form&amp;gt;元素JavaScript 对应：HTMLFormElement 类型HTMLFormElement 继承 HTMLElement自己的独有的属性和方法：

acceptCharset：服务器能够处理的字符集；等价于HTML 中的accept-charset 特性。
action：接受请求的URL；等价于HTML 中的action 特性">
<meta property="og:type" content="article">
<meta property="og:title" content="《 JavaScript 高级程序设计》备忘-第十四章-1">
<meta property="og:url" content="http://codingme.xyz/2016/10/19/javascript-note-14-1/index.html">
<meta property="og:site_name" content="CodingMe">
<meta property="og:description" content="表单脚本表单的基础知识HTML 对应： &amp;lt;form&amp;gt;元素JavaScript 对应：HTMLFormElement 类型HTMLFormElement 继承 HTMLElement自己的独有的属性和方法：

acceptCharset：服务器能够处理的字符集；等价于HTML 中的accept-charset 特性。
action：接受请求的URL；等价于HTML 中的action 特性">
<meta property="og:updated_time" content="2016-10-19T06:18:14.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="《 JavaScript 高级程序设计》备忘-第十四章-1">
<meta name="twitter:description" content="表单脚本表单的基础知识HTML 对应： &amp;lt;form&amp;gt;元素JavaScript 对应：HTMLFormElement 类型HTMLFormElement 继承 HTMLElement自己的独有的属性和方法：

acceptCharset：服务器能够处理的字符集；等价于HTML 中的accept-charset 特性。
action：接受请求的URL；等价于HTML 中的action 特性">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"right","display":"post"},
    fancybox: true,
    motion: false,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://codingme.xyz/2016/10/19/javascript-note-14-1/"/>





  <title> 《 JavaScript 高级程序设计》备忘-第十四章-1 | CodingMe </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">CodingMe</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle"></p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
  <link itemprop="mainEntityOfPage" href="http://codingme.xyz/2016/10/19/javascript-note-14-1/">

  <span style="display:none" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <meta itemprop="name" content="Huang SJ">
    <meta itemprop="description" content="">
    <meta itemprop="image" content="/uploads/avatar.jpg">
  </span>

  <span style="display:none" itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
    <meta itemprop="name" content="CodingMe">
    <span style="display:none" itemprop="logo" itemscope itemtype="http://schema.org/ImageObject">
      <img style="display:none;" itemprop="url image" alt="CodingMe" src="">
    </span>
  </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                《 JavaScript 高级程序设计》备忘-第十四章-1
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            

            

            
          </span>

          

          
            
          

          

          
          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="表单脚本"><a href="#表单脚本" class="headerlink" title="表单脚本"></a>表单脚本</h1><h2 id="表单的基础知识"><a href="#表单的基础知识" class="headerlink" title="表单的基础知识"></a>表单的基础知识</h2><p>HTML 对应： <code>&lt;form&gt;</code>元素<br>JavaScript 对应：<code>HTMLFormElement</code> 类型<br>HTMLFormElement 继承 HTMLElement<br>自己的独有的属性和方法：</p>
<ul>
<li>acceptCharset：服务器能够处理的字符集；等价于HTML 中的accept-charset 特性。</li>
<li>action：接受请求的URL；等价于HTML 中的action 特性。</li>
<li>elements：表单中所有控件的集合（HTMLCollection）。</li>
<li>enctype：请求的编码类型；等价于HTML 中的enctype 特性。</li>
<li>length：表单中控件的数量。</li>
<li>method：要发送的HTTP 请求类型，通常是”get”或”post”；等价于HTML 的method 特性。</li>
<li>name：表单的名称；等价于HTML 的name 特性。</li>
<li>reset()：将所有表单域重置为默认值。</li>
<li>submit()：提交表单。</li>
<li>target：用于发送请求和接收响应的窗口名称；等价于HTML 的target 特性。</li>
</ul>
<p>取得<code>&lt;form&gt;</code>元素引用的方式有好几种。<br>其中最常见的方式就是将它看成与其他元素一样，并为其添加id 特性，然后再像下面这样使用getElementById()方法找到它。<br>其次，通过document.forms 可以取得页面中所有的表单。在这个集合中，可以通过数值索引或name 值来取得特定的表单。<br>另外，在较早的浏览器或者那些支持向后兼容的浏览器中，也会把每个设置了name 特性的表单作为属性保存在document 对象中(不推荐使用这种方式)。<br>可以同时为表单指定id 和name 属性，但它们的值不一定相同。<br><a id="more"></a></p>
<h3 id="提交表单"><a href="#提交表单" class="headerlink" title="提交表单"></a>提交表单</h3><p>用户单击提交按钮或图像按钮时，就会提交表单。<br>使用<code>&lt;input&gt;</code>或<code>&lt;button&gt;</code>都可以定义提交按钮，只要将其type 特性的值设置为”submit”即可。<br>图像按钮则是通过将<code>&lt;input&gt;</code>的type 特性值设置为”image”来定义的。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="comment">&lt;!-- 通用提交按钮 --&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"submit"</span> <span class="attr">value</span>=<span class="string">"Submit Form"</span>&gt;</span></div><div class="line"><span class="comment">&lt;!-- 自定义提交按钮 --&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">button</span> <span class="attr">type</span>=<span class="string">"submit"</span>&gt;</span>Submit Form<span class="tag">&lt;/<span class="name">button</span>&gt;</span></div><div class="line"><span class="comment">&lt;!-- 图像按钮 --&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"image"</span> <span class="attr">src</span>=<span class="string">"graphic.gif"</span>&gt;</span></div></pre></td></tr></table></figure>
<p>只要表单中存在上面列出的任何一种按钮，那么在相应表单控件拥有焦点的情况下，按回车键就可以提交该表单。（textarea 是一个例外)<br>如果表单里没有提交按钮，按回车键不会提交表单。</p>
<p>浏览器会在将请求发送给服务器之前触发submit 事件。这样，我们就有机会验证表单数据，并据以决定是否允许表单提交。<br>阻止这个事件的默认行为就可以取消表单提交。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> form = <span class="built_in">document</span>.getElementById(<span class="string">"myForm"</span>);</div><div class="line">EventUtil.addHandler(form, <span class="string">"submit"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</div><div class="line">    <span class="comment">//取得事件对象</span></div><div class="line">    event = EventUtil.getEvent(event);</div><div class="line">    <span class="comment">//阻止默认事件</span></div><div class="line">    EventUtil.preventDefault(event);</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p>在JavaScript 中，以编程方式调用submit()方法也可以提交表单。<br>这种方式无需表单包含提交按钮，任何时候都可以正常提交表单。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> form = <span class="built_in">document</span>.getElementById(<span class="string">"myForm"</span>);</div><div class="line"><span class="comment">//提交表单</span></div><div class="line">form.submit();</div></pre></td></tr></table></figure>
<p>提交表单时可能出现的最大问题，就是重复提交表单。<br>在第一次提交表单后，如果长时间没有反应，用户可能会变得不耐烦。<br>这时候，他们也许会反复单击提交按钮。结果往往很麻烦，或者会造成错误。<br>解决这一问题的办法有两个：<br>在第一次提交表单后就禁用提交按钮，<br>或者利用onsubmit 事件处理程序取消后续的表单提交操作。</p>
<h3 id="重置表单"><a href="#重置表单" class="headerlink" title="重置表单"></a>重置表单</h3><p>用户单击重置按钮时，表单会被重置。<br>使用type 特性值为”reset”的<code>&lt;input&gt;</code>或<code>&lt;button&gt;</code>都可以创建重置按钮。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="comment">&lt;!-- 通用重置按钮 --&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"reset"</span> <span class="attr">value</span>=<span class="string">"Reset Form"</span>&gt;</span></div><div class="line"><span class="comment">&lt;!-- 自定义重置按钮 --&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">button</span> <span class="attr">type</span>=<span class="string">"reset"</span>&gt;</span>Reset Form<span class="tag">&lt;/<span class="name">button</span>&gt;</span></div></pre></td></tr></table></figure>
<p>在重置表单时，所有表单字段都会恢复到页面刚加载完毕时的初始值。<br>如果某个字段的初始值为空，就会恢复为空；而带有默认值的字段，也会恢复为默认值。</p>
<p>用户单击重置按钮重置表单时，会触发reset 事件。利用这个机会，我们可以在必要时取消重置操作。<br>与提交表单一样，也可以通过JavaScript 来重置表单。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> form = <span class="built_in">document</span>.getElementById(<span class="string">"myForm"</span>);</div><div class="line">EventUtil.addHandler(form, <span class="string">"reset"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</div><div class="line">    <span class="comment">//取得事件对象</span></div><div class="line">    event = EventUtil.getEvent(event);</div><div class="line">    <span class="comment">//阻止表单重置</span></div><div class="line">    EventUtil.preventDefault(event);</div><div class="line">&#125;);</div><div class="line"></div><div class="line"><span class="keyword">var</span> form = <span class="built_in">document</span>.getElementById(<span class="string">"myForm"</span>);</div><div class="line"><span class="comment">//重置表单</span></div><div class="line">form.reset();</div></pre></td></tr></table></figure>
<p>与调用submit()方法不同，调用reset()方法会像单击重置按钮一样触发reset 事件。<br>事实上，重置表单的需求是很少见的。更常见的做法是提供一个取消按钮，让用户能够回到前一个页面，而不是不分青红皂白地重置表单中的所有值。</p>
<h3 id="表单字段"><a href="#表单字段" class="headerlink" title="表单字段"></a>表单字段</h3><p>表单元素elements 属性，它是表单中所有表单元素（字段）的集合,是一个有序列表，<br>其中包含着表单中的所有字段，例如<code>&lt;input&gt;</code>、<code>&lt;textarea&gt;</code>、<code>&lt;button&gt;</code>和<code>&lt;fieldset&gt;</code>。<br>每个表单字段在elements 集合中的顺序，与它们出现在标记中的顺序相同，可以按照位置和name 特性来访问它们。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> form = <span class="built_in">document</span>.getElementById(<span class="string">"form1"</span>);</div><div class="line"><span class="comment">//取得表单中的第一个字段</span></div><div class="line"><span class="keyword">var</span> field1 = form.elements[<span class="number">0</span>];</div><div class="line"><span class="comment">//取得名为"textbox1"的字段</span></div><div class="line"><span class="keyword">var</span> field2 = form.elements[<span class="string">"textbox1"</span>];</div><div class="line"><span class="comment">//取得表单中包含的字段的数量</span></div><div class="line"><span class="keyword">var</span> fieldCount = form.elements.length;</div></pre></td></tr></table></figure>
<p>如果有多个表单控件都在使用一个name（如单选按钮），那么就会返回以该name 命名的一个NodeList。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">form</span> <span class="attr">method</span>=<span class="string">"post"</span> <span class="attr">id</span>=<span class="string">"myForm"</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">ul</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">li</span>&gt;</span><span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"radio"</span> <span class="attr">name</span>=<span class="string">"color"</span> <span class="attr">value</span>=<span class="string">"red"</span>&gt;</span>Red<span class="tag">&lt;/<span class="name">li</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">li</span>&gt;</span><span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"radio"</span> <span class="attr">name</span>=<span class="string">"color"</span> <span class="attr">value</span>=<span class="string">"green"</span>&gt;</span>Green<span class="tag">&lt;/<span class="name">li</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">li</span>&gt;</span><span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"radio"</span> <span class="attr">name</span>=<span class="string">"color"</span> <span class="attr">value</span>=<span class="string">"blue"</span>&gt;</span>Blue<span class="tag">&lt;/<span class="name">li</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">ul</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">form</span>&gt;</span></div></pre></td></tr></table></figure>
<p>在这个HTML 表单中，有3 个单选按钮，它们的name 都是”color”，意味着这3 个字段是一起的。<br>在访问elements[“color”]时，就会返回一个NodeList，其中包含这3 个元素；不过，如果访问elements[0]，则只会返回第一个元素。</p>
<p>我们应该尽可能使用elements。通过表单属性访问元素只是为了与旧浏览器向后兼容而保留的一种过渡方式。</p>
<h4 id="共有的表单字段属性"><a href="#共有的表单字段属性" class="headerlink" title="共有的表单字段属性"></a>共有的表单字段属性</h4><p>除了<code>&lt;fieldset&gt;</code>元素之外，所有表单字段都拥有相同的一组属性。<br>由于<code>&lt;input&gt;</code>类型可以表示多种表单字段，因此有些属性只适用于某些字段，但还有一些属性是所有字段所共有的。</p>
<ul>
<li>disabled：布尔值，表示当前字段是否被禁用。</li>
<li>form：指向当前字段所属表单的指针；只读。</li>
<li>name：当前字段的名称。</li>
<li>readOnly：布尔值，表示当前字段是否只读。</li>
<li>tabIndex：表示当前字段的切换（tab）序号。</li>
<li>type：当前字段的类型，如”checkbox”、”radio”，等等。</li>
<li>value：当前字段将被提交给服务器的值。对文件字段来说，这个属性是只读的，包含着文件在计算机中的路径。</li>
</ul>
<p>除了form 属性之外，可以通过JavaScript 动态修改其他任何属性。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> form = <span class="built_in">document</span>.getElementById(<span class="string">"myForm"</span>);</div><div class="line"><span class="keyword">var</span> field = form.elements[<span class="number">0</span>];</div><div class="line"><span class="comment">//修改value 属性</span></div><div class="line">field.value = <span class="string">"Another value"</span>;</div><div class="line"><span class="comment">//检查form 属性的值</span></div><div class="line">alert(field.form === form); <span class="comment">//true</span></div><div class="line"><span class="comment">//把焦点设置到当前字段</span></div><div class="line">field.focus();</div><div class="line"><span class="comment">//禁用当前字段</span></div><div class="line">field.disabled = <span class="literal">true</span>;</div><div class="line"><span class="comment">//修改type 属性（不推荐，但对&lt;input&gt;来说是可行的）</span></div><div class="line">field.type = <span class="string">"checkbox"</span>;</div></pre></td></tr></table></figure>
<p>能够动态修改表单字段属性，意味着我们可以在任何时候，以任何方式来动态操作表单。<br>例如，很多用户可能会重复单击表单的提交按钮。在涉及信用卡消费时，这就是个问题：因为会导致费用翻番。<br>最常见的解决方案，就是在第一次单击后就禁用提交按钮。只要侦听submit 事件，并在该事件发生时禁用提交按钮即可。<br>不能通过onclick 事件处理程序来实现这个功能，原因是不同浏览器之间存在“时差”：<br>有的浏览器会在触发表单的submit 事件之前触发click 事件，而有的浏览器则相反。<br>对于先触发click 事件的浏览器，意味着会在提交发生之前禁用按钮，结果永远都不会提交表单。<br>除了<code>&lt;fieldset&gt;</code>之外，所有表单字段都有type 属性。对于<code>&lt;input&gt;</code>元素，这个值等于HTML 特性type 的值。<br>对于其他元素，type属性有不一样的值。<br>默认<code>&lt;button&gt;</code>是submit,单选列表<code>&lt;select&gt;</code>是select-one,多选列表<code>&lt;select multiple&gt;</code>是select-multiple。<br>此外，<code>&lt;input&gt;</code>和<code>&lt;button&gt;</code>元素的type 属性是可以动态修改的，而<code>&lt;select&gt;</code>元素的type 属性则是只读的。</p>
<p>####　共有的表单字段方法</p>
<p>focus()和 blur()。<br>其中，focus()方法用于将浏览器的焦点设置到表单字段，即激活表单字段，使其可以响应键盘事件。(即激活光标(cursor)或者说游标？)<br>使用focus()方法，可以将用户的注意力吸引到页面中的某个部位。<br>(思考：类似输入信用卡或者windows激活码，输入到足够长度就跳转到下一格，是不是就是focus()的效果？)</p>
<p>例如，在页面加载完毕后，将焦点转移到表单中的第一个字段。<br>为此，可以侦听页面的load 事件，并在该事件发生时在表单的第一个字段上调用focus()方法。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">EventUtil.addHandler(<span class="built_in">window</span>, <span class="string">"load"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</div><div class="line">    <span class="built_in">document</span>.forms[<span class="number">0</span>].elements[<span class="number">0</span>].focus();</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p>如果第一个表单字段是一个<code>&lt;input&gt;</code>元素，且其type 特性的值为”hidden”，那么以上代码会导致错误。<br>另外，如果使用CSS 的display 和visibility 属性隐藏了该字段，同样也会导致错误。</p>
<p>HTML5 为表单字段新增了一个autofocus 属性。在支持这个属性的浏览器中，只要设置这个属性，不用JavaScript 就能自动把焦点移动到相应字段。<br><code>&lt;input type=&quot;text&quot; autofocus&gt;</code><br>为了保证前面的代码在设置autofocus 的浏览器中正常运行，必须先检测是否设置了该属性，如果设置了，就不用再调用focus()了。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">EventUtil.addHandler(<span class="built_in">window</span>, <span class="string">"load"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</div><div class="line">    <span class="keyword">var</span> element = <span class="built_in">document</span>.forms[<span class="number">0</span>].elements[<span class="number">0</span>];</div><div class="line">    <span class="keyword">if</span> (element.autofocus !== <span class="literal">true</span>)&#123;</div><div class="line">    element.focus(); <span class="built_in">console</span>.log(<span class="string">"JS focus"</span>);</div><div class="line">    &#125;</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p>autofocus 是一个布尔值属性，所以在支持的浏览器中它的值应该是true。</p>
<p>在默认情况下，只有表单字段可以获得焦点。对于其他元素而言，如果先将其tabIndex 属性设置为-1，然后再调用focus()方法，也可以让这些元素获得焦点。</p>
<p>与focus()方法相对的是blur()方法，它的作用是从元素中移走焦点。<br>在调用blur()方法时，并不会把焦点转移到某个特定的元素上；仅仅是将焦点从调用这个方法的元素上面移走而已。<br>在早期Web 开发中，那时候的表单字段还没有readonly 特性，因此就可以使用blur()方法来创建只读字段。(现在很少用了)</p>
<h4 id="共有的表单字段事件"><a href="#共有的表单字段事件" class="headerlink" title="共有的表单字段事件"></a>共有的表单字段事件</h4><p>除了支持鼠标、键盘、更改和HTML 事件之外，所有表单字段都支持3 个事件。</p>
<ul>
<li>blur：当前字段失去焦点时触发。</li>
<li>change：<strong>对于<code>&lt;input&gt;</code>和<code>&lt;textarea&gt;</code>元素，在它们失去焦点且value 值改变时触发；对于<code>&lt;select&gt;</code>元素，在其选项改变时触发。</strong></li>
<li>focus：当前字段获得焦点时触发。</li>
</ul>
<p>通常，可以使用focus 和blur 事件来以某种方式改变用户界面，<br>要么是向用户给出视觉提示，要么是向界面中添加额外的功能（例如，为文本框显示一个下拉选项菜单）。<br>而change 事件则经常用于验证用户在字段中输入的数据。<br>(思考：常用的地方：验证用户名是否合法？)</p>
<p>例如，假设有一个文本框，我们只允许用户输入数值。<br>此时，可以利用focus 事件修改文本框的背景颜色，以便更清楚地表明这个字段获得了焦点。<br>可以利用blur 事件恢复文本框的背景颜色，利用change 事件在用户输入了非数值字符时再次修改背景颜色。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> textbox = <span class="built_in">document</span>.forms[<span class="number">0</span>].elements[<span class="number">0</span>];</div><div class="line">EventUtil.addHandler(textbox, <span class="string">"focus"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</div><div class="line">    event = EventUtil.getEvent(event);</div><div class="line">    <span class="keyword">var</span> target = EventUtil.getTarget(event);</div><div class="line">    <span class="keyword">if</span> (target.style.backgroundColor != <span class="string">"red"</span>)&#123;</div><div class="line">        target.style.backgroundColor = <span class="string">"yellow"</span>;</div><div class="line">    &#125;</div><div class="line">&#125;);</div><div class="line">EventUtil.addHandler(textbox, <span class="string">"blur"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</div><div class="line">    event = EventUtil.getEvent(event);</div><div class="line">    <span class="keyword">var</span> target = EventUtil.getTarget(event);</div><div class="line">    <span class="keyword">if</span> (<span class="regexp">/[^\d]/</span>.test(target.value))&#123;</div><div class="line">        target.style.backgroundColor = <span class="string">"red"</span>;</div><div class="line">    &#125; <span class="keyword">else</span> &#123;</div><div class="line">        target.style.backgroundColor = <span class="string">""</span>;</div><div class="line">    &#125;</div><div class="line">&#125;);</div><div class="line">EventUtil.addHandler(textbox, <span class="string">"change"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</div><div class="line">    event = EventUtil.getEvent(event);</div><div class="line">    <span class="keyword">var</span> target = EventUtil.getTarget(event);</div><div class="line">    <span class="keyword">if</span> (<span class="regexp">/[^\d]/</span>.test(target.value))&#123;</div><div class="line">        target.style.backgroundColor = <span class="string">"red"</span>;</div><div class="line">    &#125; <span class="keyword">else</span> &#123;</div><div class="line">        target.style.backgroundColor = <span class="string">""</span>;</div><div class="line">    &#125;</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p>onfocus 事件处理程序将文本框的背景颜色修改为黄色，以清楚地表明当前字段已经激活。<br>onblur 和onchange 事件处理程序则会在发现非数值字符时，将文本框背景颜色修改为红色。</p>
<p>在某些浏览器中，blur事件会先于change 事件发生；而在其他浏览器中，则恰好相反。<br>为此，不能假定这两个事件总会以某种顺序依次触发。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Web/" rel="tag"># Web</a>
          
            <a href="/tags/JavaScript/" rel="tag"># JavaScript</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/10/18/javascript-note-13-8/" rel="next" title="《 JavaScript 高级程序设计》备忘-第十三章-8">
                <i class="fa fa-chevron-left"></i> 《 JavaScript 高级程序设计》备忘-第十三章-8
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/10/19/javascript-note-14-2/" rel="prev" title="《 JavaScript 高级程序设计》备忘-第十四章-2">
                《 JavaScript 高级程序设计》备忘-第十四章-2 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/avatar.jpg"
               alt="Huang SJ" />
          <p class="site-author-name" itemprop="name">Huang SJ</p>
          <p class="site-description motion-element" itemprop="description"></p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">75</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">4</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">9</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/hsj1992" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/hsj9527" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/u/1694147905" target="_blank" title="Weibo">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  Weibo
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.freecodecamp.cn/hsj1992" target="_blank" title="FreeCodeCamp">
                  
                    <i class="fa fa-fw fa-fire"></i>
                  
                  FreeCodeCamp
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://codepen.io/hsj1992/" target="_blank" title="codepen">
                  
                    <i class="fa fa-fw fa-codepen"></i>
                  
                  codepen
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://hsj1992.oschina.io/" target="_blank" title="码云镜像">
                  
                    <i class="fa fa-fw fa-code"></i>
                  
                  码云镜像
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://hsj1992.coding.me/" target="_blank" title="coding镜像">
                  
                    <i class="fa fa-fw fa-code"></i>
                  
                  coding镜像
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://hsj1992.github.io/" target="_blank" title="github镜像">
                  
                    <i class="fa fa-fw fa-code"></i>
                  
                  github镜像
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://codingme-6dd8a.firebaseapp.com" target="_blank" title="Firebase镜像">
                  
                    <i class="fa fa-fw fa-google"></i>
                  
                  Firebase镜像
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#表单脚本"><span class="nav-number">1.</span> <span class="nav-text">表单脚本</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#表单的基础知识"><span class="nav-number">1.1.</span> <span class="nav-text">表单的基础知识</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#提交表单"><span class="nav-number">1.1.1.</span> <span class="nav-text">提交表单</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#重置表单"><span class="nav-number">1.1.2.</span> <span class="nav-text">重置表单</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#表单字段"><span class="nav-number">1.1.3.</span> <span class="nav-text">表单字段</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#共有的表单字段属性"><span class="nav-number">1.1.3.1.</span> <span class="nav-text">共有的表单字段属性</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#共有的表单字段事件"><span class="nav-number">1.1.3.2.</span> <span class="nav-text">共有的表单字段事件</span></a></li></ol></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2015 - 
  <span itemprop="copyrightYear">2016</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Huang SJ</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="//cdn.staticfile.org/jquery/2.1.3/jquery.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/fastclick/1.0.6/fastclick.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/jquery_lazyload/1.9.7/jquery.lazyload.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/velocity/1.2.1/velocity.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/velocity/1.2.1/velocity.ui.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/fancybox/2.1.5/jquery.fancybox.pack.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	




  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
      search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = $( "entry", xmlResponse ).map(function() {
            return {
              title: $( "title", this ).text(),
              content: $("content",this).text(),
              url: $( "url" , this).text()
            };
          }).get();
          var $input = document.getElementById(search_id);
          var $resultContent = document.getElementById(content_id);
          $input.addEventListener('input', function(){
            var matchcounts = 0;
            var str='<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length > 1) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var content_index = [];
                var data_title = data.title.trim().toLowerCase();
                var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                var data_url = decodeURIComponent(data.url);
                var index_title = -1;
                var index_content = -1;
                var first_occur = -1;
                // only match artiles with not empty titles and contents
                if(data_title != '') {
                  keywords.forEach(function(keyword, i) {
                    index_title = data_title.indexOf(keyword);
                    index_content = data_content.indexOf(keyword);
                    if( index_title >= 0 || index_content >= 0 ){
                      isMatch = true;
                      if (i == 0) {
                        first_occur = index_content;
                      }
                    }

                  });
                }
                // show search results
                if (isMatch) {
                  matchcounts += 1;
                  str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                  var content = data.content.trim().replace(/<[^>]+>/g,"");
                  if (first_occur >= 0) {
                    // cut out 100 characters
                    var start = first_occur - 20;
                    var end = first_occur + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if(start == 0){
                      end = 50;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    var match_content = content.substring(start, end);
                    // highlight all keywords
                    keywords.forEach(function(keyword){
                      var regS = new RegExp(keyword, "gi");
                      match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                    });

                    str += "<p class=\"search-result\">" + match_content +"...</p>"
                  }
                  str += "</li>";
                }
              })};
            str += "</ul>";
            if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
            if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
            $resultContent.innerHTML = str;
          });
          proceedsearch();
        }
      });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  

  

  

  


</body>
</html>
